package source.events.action;

import source.model.*;
import source.model.type.ActionResult;
import source.model.type.GameObjectType;
import source.model.type.UnitType;
import source.view.MainScreen;

/**
 * BuildUnit queues up a unit to be built at the current base.  If the current
 * selection is not a base, the action fails.
 * @author Joe
 *
 */
public class BuildUnit implements Action{

	private UnitType uType;
	private int playerID;
	private Base base;
	
	public BuildUnit(UnitType u, int playerID)
	{
		this.uType = u;
		this.playerID = playerID;
	}
	
	public ActionResult execute( DataHandler dh ) {
		GameObject go = dh.getCurrentSelection();

		if(go.objectType() != GameObjectType.BASE)
		{
			MainScreen.writeToConsole("Current selection is not an base");
			return ActionResult.IMPOSSIBLE;
		}
		
		this.base = (Base)go;
		
		// decrement ore and add unit to the base queue
		if (dh.getPlayer(playerID).decrementOre(uType.ore())) {
			//set the manpower left to the new unit added
			if (this.base.emptyMission()){
				this.base.setMPleft(uType.manpower());
			}
			//add unit to base queue
			this.base.addMission(uType);
			MainScreen.writeToConsole(uType + " has been added to the build queue");
		}
		else {
			MainScreen.writeToConsole("Not enough ore to build unit");
			return ActionResult.FAILED;
		}		
		
		dh.returnObject(base);
		
		return ActionResult.SUCCESS;
	}
}
